package com.iot.mqtt;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.UUID;


/**
 *
 * Title:Server
 * Description: 服务器向多个客户端推送主题，即不同客户端可向服务器订阅相同主题
 *
 */
public class Server {

   // public static final String HOST = "tcp://47.94.195.238:1883";
   // public static final String TOPIC = "test-topic";
    private static final String clientid = "server";

    protected MqttClient server;
    //public MqttTopic topic;
//    private MqttTopic topic125;
   // private String userName = "admin";
   // private String passWord = "password";

    public MqttMessage message;

    public Server() {

        try {
            connect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    protected void connect() throws MqttException {
        // MemoryPersistence设置clientid的保存形式，默认为以内存保存
        server = new MqttClient(MQCommon.HOST, UUID.randomUUID().toString(), new MemoryPersistence());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
        options.setUserName(MQCommon.USERNAME);
        options.setPassword(MQCommon.PASSWORD.toCharArray());
        // 设置超时时间
        options.setConnectionTimeout(10);
        // 设置会话心跳时间
        options.setKeepAliveInterval(20);
        try {
            server.setCallback(new ServerCallback(this));
            server.connect(options);
           // topic = client.getTopic(TOPIC);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void publish(String topic,String message, int qos) throws MqttPersistenceException, MqttException {
        MqttMessage mqttMessage = new MqttMessage(message.getBytes());
        mqttMessage.setQos(qos);
        server.publish(topic, mqttMessage);
    }

    public static void main(String[] args) throws MqttException {
//        Server server = new Server();
//        server.message = new MqttMessage();
//        server.message.setQos(2);
//        server.message.setRetained(true);
//        server.message.setPayload("可以了abc1".getBytes());
//        server.publish(server.topic , server.message);
//
//        System.out.println(server.message.isRetained() + "------ratained状态");
    }
}
